import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { Button, Form, Row, Spin, Steps } from 'antd';
import { useRequest } from 'ahooks';
import CodeEditor from '@/components/CodeEditor';
import Mapper from '@/pages/Transformer/components/Mapper';
import request from '@/utils/request';
import ProcessForm from '../ProcessForm';
import { serialize } from '@/pages/Transformer/components/SourcePanel/utils';

const { Step } = Steps;

const steps = [
  {
    title: '流程基本信息',
    content: 'First-content',
  },
  {
    title: '初始报文',
    content: 'Second-content',
  },
  {
    title: '业务实例信息',
    content: 'Last-content',
  },
];

function ProcessCreateStepForm({ form, ...data }, ref) {
  const { getFieldDecorator } = form;
  const [current, _setCurrent] = useState(0);
  const editorRef = useRef();

  useImperativeHandle(ref, () => ({
    ...form,
    getFieldsValue: () => ({
      ...form.getFieldsValue(),
      initContent: editorRef.current.getValue(),
      initContentFormat: editorRef.current.getFormat(),
    }),
  }));

  const { data: tree, loading: treeLoading, run: loadTree } = useRequest(
    () => {
      const editor = editorRef.current;
      if (!editor.getValue()) {
        return Promise.resolve(null);
      }
      return request.post(`/transform/parseSourceTree`, {
        data: {
          format: editor.getFormat(),
          message: editor.getValue(),
        },
      });
    },
    {
      manual: true,
    }
  );

  const treeData = tree ? serialize([tree]) : [];

  const setCurrent = target => {
    if (current === 1) {
      loadTree();
    }
    _setCurrent(target);
  };

  return (
    <>
      <Steps style={{ marginBottom: 24 }} current={current} onChange={setCurrent}>
        {steps.map(item => (
          <Step key={item.title} title={item.title} />
        ))}
      </Steps>
      <div style={{ display: current === 0 ? '' : 'none' }}>
        <ProcessForm form={form} {...data} />
      </div>
      <div style={{ display: current === 1 ? '' : 'none' }}>
        <CodeEditor ref={editorRef} switchable height={481} />
      </div>
      <div style={{ display: current === 2 ? '' : 'none' }}>
        <Spin spinning={treeLoading}>
          <Form.Item label="实例ID">
            {getFieldDecorator('instanceIdPath')(<Mapper treeData={treeData} />)}
          </Form.Item>
          <Form.Item label="轨迹ID">
            {getFieldDecorator('traceIdPath')(<Mapper treeData={treeData} />)}
          </Form.Item>
          <Form.Item label="分片键">
            {getFieldDecorator('shardingKeyPath')(<Mapper treeData={treeData} />)}
          </Form.Item>
        </Spin>
      </div>
      <Row style={{ marginTop: 16 }} type="flex" justify="center">
        {current > 0 && <Button onClick={() => setCurrent(current => current - 1)}>上一步</Button>}
        {current < steps.length - 1 && (
          <Button
            style={{ marginLeft: 8 }}
            type="primary"
            onClick={() => setCurrent(current => current + 1)}
          >
            下一步
          </Button>
        )}
      </Row>
    </>
  );
}

export default forwardRef(ProcessCreateStepForm);
